from lxml import etree
import requests
from Tool.NetTool import GetHttpclient
import xml.etree.ElementTree as ET
import html


def are_elements_equal(elem1, elem2):
    if elem1.tag != elem2.tag:
        return False
    if elem1.attrib != elem2.attrib:
        return False
    if elem1.text != elem2.text:
        return False
    if len(elem1) != len(elem2):
        return False
    else:
        for child1, child2 in zip(elem1, elem2):
            if not are_elements_equal(child1, child2):
                return False
    return True


def jldjf(elem1, elem2):
    if etree.tostring(elem1) == etree.tostring(elem2):
        return elem1
    else:
        if elem1.tag == elem2.tag:
            if len(elem1) == 0:
                # elem1.text = '模板差异1'
                print('单体内容差异' + ':' + elem1.tag)
                keys = elem1.keys()
                for key in keys:
                    if elem1.attrib[key] == elem2.attrib[key]:
                        print(key + ':' + elem1.attrib[key])
                    else:
                        print(key + ':' + elem1.attrib[key])
                        print(key + ':' + elem2.attrib[key])
                if elem1.text != elem2.text:
                    print('text:' + html.unescape(elem1.text))
                    print('text:' + html.unescape(elem2.text))
                print('\r\n')
                return elem1
            elif len(elem1) != len(elem2):
                print('大多体内容差异')
                print(html.unescape(etree.tostring(elem1).decode('utf-8')))
                print(html.unescape(etree.tostring(elem2).decode('utf-8')))
                print('\r\n')
            else:
                for child1, child2 in zip(elem1, elem2):
                    jldjf(child1, child2)
                return elem1
        else:
            print('多体内容差异')
            print(html.unescape(etree.tostring(elem1).decode('utf-8')))
            print(html.unescape(etree.tostring(elem2).decode('utf-8')))
            print('\r\n')
            return elem1


def digui(elMun):
    for el in elMun.getchildren():
        print(el.tag)
        print(etree.xpath.tostring(el))
        digui(el)


if __name__ == '__main__':
    htmlCode = html.unescape(GetHttpclient(f''))
    tree_html = etree.HTML(htmlCode)
    htmlCode2 = html.unescape(GetHttpclient(f''))
    tree_html2 = etree.HTML(htmlCode2)
    elex = jldjf(tree_html, tree_html2)
    # print(etree.tostring(elex).decode('utf-8'))
    # print(etree.tostring(elex).decode('utf-8'))
    xpath_a = '//a'
    # print(tree_html)
    # print(type)
    jj = etree.tostring(tree_html).decode('utf-8')
    r_list = tree_html.xpath(xpath_a)
    # print(r_list[10].text)
    # print(r_list[10].get('href'))
    # print(etree.tostring(r_list[0]).decode('utf-8'))
    # print(tree_html.tag)
    # print(len(tree_html.getchildren()))

    # digui(tree_html)

    # print(jj)

    title = tree_html.xpath('//title/text()')
    tree_html.xpath('//title')
    print(title)
